package cn.sunshine.basic.service.impl;

import cn.sunshine.basic.constant.BaseContants;
import cn.sunshine.basic.dto.LoginDto;
import cn.sunshine.basic.dto.WXLoginDto;
import cn.sunshine.basic.exception.BusinessException;
import cn.sunshine.basic.service.ILoginService;
import cn.sunshine.basic.utils.*;
import cn.sunshine.user.domain.Logininfo;
import cn.sunshine.user.domain.User;
import cn.sunshine.user.domain.Wxuser;
import cn.sunshine.user.mapper.LogininfoMapper;
import cn.sunshine.user.mapper.UserMapper;
import cn.sunshine.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public Map<String, Object> account(LoginDto loginDto) {
        String username = loginDto.getUsername();
        String password = loginDto.getPassword();
        String type = loginDto.getType();
        // 1.参数为空校验
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password) || StringUtils.isEmpty(type)) {
            throw new BusinessException("参数不能为空！");
        }
        // 2.根据账号和type类型查询用户，字段对应有三个username or phone or email and type
        Logininfo logininfo = logininfoMapper.loadByUsernameAndType(username, type);
        // 3.判断账号是否存在，不存在抛出异常
        if (logininfo == null) {
            throw new BusinessException("账号密码错误，请重新输入！");
        }
        // 4.判断密码是否一致，需要加盐加密比较
       String passwordTmp = MD5Utils.encrypByMd5(logininfo.getSalt() + password );
        System.out.println(logininfo.getSalt());
        System.out.println(password);
        System.out.println(passwordTmp);
        System.out.println(logininfo.getPassword());
        if (!logininfo.getPassword().equals(passwordTmp)) {
            throw new BusinessException("账号密码错误，请重新输入！");
        }
        // 5.生成UUID作为key
        String token = UUID.randomUUID().toString();
        // 6.将UUID和logininfo设置到redis中，设置30分钟有效期
        redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
        // 7.把Logininfo对象的敏感信息置为空，作为value
        logininfo.setSalt("");
        logininfo.setPassword("");
        // 8.将UUID和logininfo存入到map中，返回给前端
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("logininfo", logininfo);
        return map;
    }

    /*
     * @Title: wechat
     * @Description: 微信登录二部曲，根据code获取accessToken
     * @Author: Mr.Jiang
     * @Version: 1.0
     * @Date:  2022/7/10 18:42
     * @Parameters: [wxLoginDto]
     * @Return cn.sunshine.basic.utils.AjaxResult
     */
    @Override
    public AjaxResult wechat(WXLoginDto wxLoginDto) {
        String code = wxLoginDto.getCode();
        // 1.判断参数是否为空
        if (StringUtils.isEmpty(code)) {
            throw new BusinessException("参数为空，请重新传递！");
        }
        // 2.拼接二步曲请求地址，获取access_token、openid
        String tokenUrl = BaseContants.WechatConstant.TOKEN_URL
                .replace("APPID", BaseContants.WechatConstant.APPID)
                .replace("SECRET", BaseContants.WechatConstant.SECRET)
                .replace("CODE", code);
        // 3.发起请求获取到JSON字符串
        String jsonStr = HttpClientUtils.httpGet(tokenUrl);
        // 4.将字符串JSON转换为JSON对象，获取到access_token&openid
        JSONObject jsonObj = JSONObject.parseObject(jsonStr);
        String accessToken = jsonObj.getString("access_token");
        String openId = jsonObj.getString("openid");
        // 5.根据openId查询t_wxuser
        Wxuser wxuser = wxuserMapper.loadByOpenId(openId);
        // 6.判断微信用户信息是否存在
        if (wxuser != null && wxuser.getUserId() != null) {
            // 6.1.wx用户存在并且已经绑定了账号，直接免密登录
            // - 根据wxuser中的userid查询logininfo信息
            Logininfo logininfo = logininfoMapper.loadByUserId(wxuser.getUserId());
            // 生成UUID作为token存入到redis中设置有效期30分钟
            String token = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(
                    token,
                    logininfo,
                    30,
                    TimeUnit.MINUTES
            );
            // 5.将用户敏感信息置空
           // logininfo.setPassword("");
            //logininfo.setSalt("");
            // 6.并设置token和用户信息到map中
            HashMap<String, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("logininfo", logininfo);
            return AjaxResult.getAjaxResult().setResultObj(map);
        }

        // 6.2.不存在告诉前端用户跳转到账号绑定页面，传递参数到前端，因为我们在下个接口需要使用
        StringBuffer paramStr = new StringBuffer()
                .append("?accessToken=")
                .append(accessToken)
                .append("&openId=").append(openId);
        return AjaxResult.getAjaxResult().setSuccess(false).setResultObj(paramStr);
    }
/* 
* @Title: binder
* @Description: 微信登录绑定账号
* @Author: Mr.Jiang
* @Version: 1.0
* @Date:  2022/7/10 20:16  
* @Parameters: [wxLoginDto]
* @Return java.util.Map<java.lang.String,java.lang.Object>
*/
    @Override
    @Transactional
    public Map<String, Object> binder(WXLoginDto wxLoginDto) {
        // 1.非空校验

        String verifyCode = wxLoginDto.getVerifyCode();
        String phone = wxLoginDto.getPhone();
        String accessToken = wxLoginDto.getAccessToken();
        String openId = wxLoginDto.getOpenId();
        if (StringUtils.isEmpty(verifyCode)
                || StringUtils.isEmpty(phone)
                || StringUtils.isEmpty(accessToken)
                || StringUtils.isEmpty(openId)){
            throw new BusinessException("参数异常！");
        }
        // 2.手机验证码校验
        // 1.为空校验o
        String phoneCodeKey = BaseContants.verifyCodeConstant.BUSINESS_BINDER_KEY + phone;
        Object phoneCodeValueRedis = redisTemplate.opsForValue().get(phoneCodeKey);
        // 3.判断验证码是否正确
        String phoneCode = phoneCodeValueRedis.toString().split(":")[1];
        if (!phoneCode.equalsIgnoreCase(verifyCode)){
            throw new BusinessException("手机验证码错误，请重新输入！");
        }
        // 3.根据手机号查询用户是否存在
        User user = userMapper.loadByPhone(phone);
        // 3.1.不存在：初始化user&logininfo并保存
        Logininfo logininfo = null;
        if (user == null){
            user = smsCodeDto2User(phone);
            logininfo = user2Logininfo(user);
            logininfoMapper.save(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);
        }else {// 3.2.存在：查询Logininfo
            logininfo = logininfoMapper.loadByUserId(user.getId());
        }
        // 4.根据前端传递的accessToken&openId查询微信用户基本信息
        String wxUserUrl = BaseContants.WechatConstant.WXUSER_URL
                .replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        String wxUserStr = HttpClientUtils.httpGet(wxUserUrl);
        // 5.通过JSONObject方法将JSON字符串转换为指定对象
        Wxuser wxuser = JSONObject.parseObject(wxUserStr, Wxuser.class);
        // 5.保存wxUser对象，并且需要设置userId字段为user对象的主键
        wxuser.setUserId(user.getId());
        wxuserMapper.save(wxuser);
        // 6.返回成功登录map
        // 5.生成UUID作为key
        String token = UUID.randomUUID().toString();
        // 6.将uuid&&logininfo设置到redis中，设置30分钟有效期
        redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
        // 7.把Logininfo对象的敏感信息置为空，作为value
       logininfo.setSalt("");
       logininfo.setPassword("");
        // 8.将uuid&&logininfo存入到map中，返回给前端
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("logininfo", logininfo);
        return map;

    }


    private User smsCodeDto2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String saltPassword = MD5Utils.encrypByMd5( "1"+ salt);
        user.setPassword(saltPassword);
        user.setSalt(salt);
        // 此处最好给用户发个短信，告知他初始密码是多少
        return user;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        return logininfo;
    }
}